package com.xu.ai.chatclient.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;

import jakarta.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * servlet工具类
 *
 * @author xuguan
 * @since 2025/10/17
 */
public class ServletUtil {

	public static void showImageResponse(String url) {
		if (StringUtils.hasText(url)) {
			try (InputStream is = URI.create(url).toURL().openStream()) {
				final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
					.currentRequestAttributes();
				final HttpServletResponse response = requestAttributes.getResponse();
				// 设置图片的Content-Type
				response.setContentType(MediaType.IMAGE_JPEG_VALUE); // 根据实际图片类型调整
				// 获取response输出流并写入图片数据
				OutputStream os = response.getOutputStream();
				os.write(is.readAllBytes());
				os.flush();
			}
			catch (IOException e) {
				throw new RuntimeException("Failed to read or write image: " + url, e);
			}
		}
	}

}
